//
//  logxiangqingTableViewController.m
//  shuilijuOASystem
//
//  Created by michael on 16/8/9.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "MHDatePicker.h"
#import "logxiangqingTableViewController.h"
#import "GDataDefines.h"
@interface logxiangqingTableViewController ()
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property (nonatomic,strong)NSMutableArray *mutArray;

@property (strong, nonatomic) MHDatePicker *selectDatePicker;

@end

@implementation logxiangqingTableViewController

- (void)viewDidLoad {
self.view.backgroundColor = [UIColor whiteColor];
[self setupTitle];
    [super viewDidLoad];
    self.title = @"详情";
          NSDate *currentDate = [NSDate date];//获取当前时间，日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd "];
_dateString = [dateFormatter stringFromDate:currentDate];

    [self loadMore];
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keybordDown)];
    [self.view addGestureRecognizer:tap];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)keybordDown {
 
    [self.view endEditing:YES];
        }
-(void)setupTitle{

_rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
_rightButton.frame = CGRectMake(0, 0, 44, 44);
                [_rightButton addTarget:self action:@selector(createNewSMSAction) forControlEvents:UIControlEventTouchUpInside];
                    [_rightButton setTitle:@"编辑" forState:UIControlStateNormal];
       [_rightButton setTitle:@"发送" forState:UIControlStateSelected];
                    [_rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                 
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];


//    _rightItem1  = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(createNewSMSAction)];
//   
//   _rightItem2   = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
// 
//    [self.navigationItem setRightBarButtonItems:@[_rightItem2,_rightItem1]];

    
   
}
-(void)createNewSMSAction{
         if ([_rightButton.titleLabel.text isEqualToString:@"发送"]) {
             [self.view endEditing:YES];

NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
 NSString *json =[NSString stringWithFormat: @"{'newsAuthor':'%@','newsContent':'%@', 'postTime':'%@'}",userId,_workplaceField.text,_timeField.text];

NSString *str = [NSString stringWithFormat:@"%@",_dic[@"id"]];
    NSArray * array = @[@{@"id":str},@{@"json":json},@{@"sName":userId}];
           [HttpTools postWithURL:exchdialylog
     arrays:array method:@"ModDaily" success:^(id JSON) {
     NSData * data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
       GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
         GDataXMLElement *rootElement = [doc rootElement];
    
     NSArray *infoData= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoData count];i++)
    {
        GDataXMLElement *infoElement = [infoData objectAtIndex:i];
        self.infoString = [infoElement stringValue];
    }


     if ([_infoString isEqualToString:@"11"]) {
     [self.view makeToast:@"发送成功!"];
     [self.navigationController popViewControllerAnimated:YES];
}else{
 [self.view makeToast:@"发送失败!"];
      }
      
    } failure:^(NSError *error) {
        
    }];
 
}
  else{
   [_rightButton setTitle:@"发送" forState:UIControlStateNormal];

   if(_nameField.editable||_databutton.enabled||_workplaceField.editable){
   
   self.editing = NO;
   _databutton.enabled = NO;
   }
   else{
   
   _nameField.editable = YES;
   _databutton.enabled = YES;
   _workplaceField.editable = YES;
   }

  
  }
   
}
- (void)searchAction{

  



}
- (void)initview{
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight) style:UITableViewStylePlain];
_tableView.dataSource = self;
_tableView.delegate = self;
_tableView.bounces = NO;
[self.view addSubview:_tableView];

}
- (void)loadMore{
 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unid":_field},@{@"userId":userId}];
           [HttpTools requestWithURL:@"exchdialylog"
     arrays:array method:@"contentDaily" success:^(id JSON) {
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
       NSArray *array = JSON[@"content"];
       
       _dic = [array firstObject];
_name = [NSString stringWithFormat:@"%@",_dic[@"newsAuthor"]];
_time = _dic[@"postTime"];
_context = [NSString stringWithFormat:@"%@",_dic[@"newsContent"]];
    [self initview];

//        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
     [self.tableView headerEndRefreshing];
        
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 

if (indexPath.row==0) {
 
  static NSString *cellid0 = @"cell0";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid0];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid0];     cell.selectionStyle = UITableViewCellSelectionStyleNone;
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"发布姓名 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _nameField = [[UITextView alloc]init];
      _nameField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
//      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
//      _nameField.backgroundColor = myColor;
 [_nameField setFont:[UIFont systemFontOfSize:13]];
 _nameField.textAlignment = NSTextAlignmentLeft;

       [cell.contentView addSubview:_nameField];

       }
                  _nameField.editable = NO;

             _nameField.text = _name;

             return cell;

}


else if (indexPath.row==1) {

static NSString *cellid6 = @"cell6";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid6];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid6];
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"发布时间 :";
    
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
//      _timeField = [[UITextView alloc]init];
//      _timeField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
//      _timeField.text = _dateString;
//      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
//      _timeField.backgroundColor = myColor;
// [_timeField setFont:[UIFont systemFontOfSize:13]];
// _timeField.textAlignment = NSTextAlignmentLeft;
//      _timeField.delegate = self;
//       [cell.contentView addSubview:_timeField ];
    
    _databutton = [UIButton buttonWithType:UIButtonTypeCustom];
      _databutton.frame = CGRectMake(label.right, label.top, 120, label.height);
//    _button1.backgroundColor = [UIColor yellowColor];
    _databutton.titleLabel.font = [UIFont systemFontOfSize: 13.0];
    
                 [_databutton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
           [_databutton addTarget:self action:@selector(dataaction) forControlEvents:UIControlEventTouchUpInside];
if(self.editing){

_databutton.enabled = YES;
}else{

_databutton.enabled = NO;

}
 
       [cell.contentView addSubview:_databutton];
}
             [_databutton setTitle:_dateString forState:UIControlStateNormal];

             return cell;

}
else  {

static NSString *cellid2 = @"cell2";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid2];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid2];
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 30)];
    label.text = @"内容 :";
        label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _workplaceField = [[UITextView alloc]init];
          CGFloat  titleFloat  = [OAToolBox sizebyText:_dic[@"newsContent"] font:13 minsWidth:40];
NSLog(@"- - -  %f",titleFloat);
if (titleFloat<40){
      _workplaceField.frame = CGRectMake(20, label.bottom, KScreenWidth-40, titleFloat+40);


}else{
      _workplaceField.frame = CGRectMake(20, label.bottom, KScreenWidth-40, titleFloat+10);}
//_workplaceField.backgroundColor = [UIColor redColor];
 [_workplaceField setFont:[UIFont systemFontOfSize:13]];
_workplaceField.delegate = self;
 _workplaceField.textAlignment = NSTextAlignmentLeft;

       [cell.contentView addSubview:_workplaceField];

       }
_workplaceField.text =_context;
                         _workplaceField.editable = NO;

             return cell;

}

}

//日期选择
- (void)dataaction{
 _selectDatePicker = [[MHDatePicker alloc] init];
    _selectDatePicker.isBeforeTime = YES;
    _selectDatePicker.datePickerMode = UIDatePickerModeDate;
    
    __weak typeof(self) weakSelf = self;
    [_selectDatePicker didFinishSelectedDate:^(NSDate *selectedDate) {
      NSString *string = [weakSelf dateStringWithDate:selectedDate DateFormat:@"yyyy-MM-dd"];
  _dateString = [string stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
_dateString = [_dateString stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
_dateString = [_dateString stringByReplacingOccurrencesOfString:@"日" withString:@""];
      
      
[self.tableView reloadData];
      [weakSelf.databutton setTitle:string forState:UIControlStateNormal];
    }];

}
- (NSString *)dateStringWithDate:(NSDate *)date DateFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    NSString *str = [dateFormatter stringFromDate:date];
    return str ? str : @"";
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 2) {
          CGFloat  titleFloat  = [OAToolBox sizebyText:_dic[@"newsContent"] font:13 minsWidth:40];
          if (titleFloat<40) {
    return 60;
}else{
          return titleFloat +40;}
}
else{
return 40;
}
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}


@end
